import jsonfile from 'jsonfile'
import { Message, Middleware } from 'mirai-js'
import { Bot as BotType } from 'mirai-js/dist/node/index'
import Rcon from 'rcon-srcds'
import { textCommandFilter } from '../../middleware/textCommandFilter'
export default (bot: BotType) => {
  bot.on(
    'GroupMessage',
    new textCommandFilter('list').done(async (data) => {
      const file = jsonfile.readFileSync('./src/config/get_mc/config.json')
      const currentGroupId: number = data.sender.group.id
      const CumcServer = data.text || 'default'
      let currentServe = null
      // 取出当前选择的ip
      if (file.servers[currentGroupId]) {
        file.servers[currentGroupId].servers.some((item) => {
          if (item.name === CumcServer) {
            currentServe = item
          }
        })
      }
      if (!currentServe) {
        console.error(`当前群聊${currentGroupId}未配置服务器信息或指定的服务器不存在${CumcServer}`)
        return
      }
      const RconServer = new Rcon({ host: currentServe.host, port: currentServe.rconPort, timeout: 5000 })
      try {
        await RconServer.authenticate(currentServe.rconPasswrd)
      } catch (err) {
        return bot.sendMessage({
          group: data.sender.group.id,
          message: new Message().addText(`${JSON.stringify(err)}`),
        })
      }
      let list = await RconServer.execute('list')
      bot.sendMessage({
        group: data.sender.group.id,
        message: new Message().addText(`${list}`),
      })
    }),
  )
}
